<template>
  <div style="padding: 10px">
    <a-card size="small">
      <a-form layout="vertical">
        <a-row :gutter="12">
          <a-col :span="6">
            <a-form-item label="关键字">
              <a-input
                v-model:value="searchParams.keywords"
                placeholder="请输入人员姓名或手机号"
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item>
              <template #label>
                <span>所属业户</span>
              </template>
              <TenantComponent
                :ownerId="searchParams.owner_id"
                :allowes="true"
                :titleser="'所属业户'"
                @selectcancel="selectCancel"
                @changeallowes="changeallowes"
                @request="$utils.commonRequest"
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item>
              <template #label>
                <span>所属{{ $L("楼宇") }}</span>
              </template>
              <a-select
                :placeholder="buildPlaceholder"
                v-model:value="searchParams.build_id"
                :options="buildList"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="用户身份">
              <a-select
                placeholder="请选择用户身份"
                v-model:value="searchParams.type"
                :options="typeList"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="审核状态">
              <a-select
                placeholder="请选择审核状态"
                v-model:value="searchParams.status"
                :options="statusList"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label=" ">
              <a-space>
                <a-button @click="reset">重置</a-button>
                <a-button type="primary" @click="getDataList(true)">
                  搜索
                </a-button>
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-card style="margin-top: 10px" size="small">
      <a-table
        :columns="columns"
        :dataSource="dataList"
        bordered
        :pagination="pagination"
        @change="HouseholdChange"
        rowKey="id"
        :scroll="{ x: 'max-content' }"
      >
        <template #title>
          <a-row type="flex" align="middle" justify="space-between">
            <a-col>业户人员列表</a-col>
            <a-col>
              <a-space>
                <a-button type="primary" ghost @click="ICCardView()">
                  IC卡管理
                </a-button>
                <a-button type="primary" @click="HouseholdEdit()">
                  <template #icon>
                    <PlusOutlined />
                  </template>
                  添加业户人员
                </a-button>
                <a-dropdown>
                  <template #overlay>
                    <a-menu>
                      <a-menu-item @click="btnUserImport" key="btnUserImport"
                        >业户人员导入</a-menu-item
                      >
                      <a-menu-item @click="userProfile" key=" userProfile"
                        >人员配置</a-menu-item
                      >
                    </a-menu>
                  </template>
                  <a-button>
                    更多
                    <DownOutlined />
                  </a-button>
                </a-dropdown>
              </a-space>
            </a-col>
          </a-row>
        </template>
        <template #bodyCell="{ text, record, index, column }">
          <template v-if="column.key === 'status'">
            <a-badge
              v-if="record.status == 0"
              status="warning"
              :text="record.status_txt"
            />
            <a-badge
              v-if="record.status == 1"
              status="success"
              :text="record.status_txt"
            />
            <a-badge
              v-if="record.status == 4"
              status="error"
              :text="record.status_txt"
            />
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" @click="ICCardView(record)">
                IC卡
              </a-button>
              <a-button type="link" @click="HouseholdEdit(record)"
                >编辑</a-button
              >
              <a-button type="link" danger @click="HouseholdDelet(record)">
                删除
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 编辑租客员工管理 -->
    <HouseholdEdit
      :visible="visible"
      :id="idEdit"
      :ownerInfo="ownerInfoEdit"
      @onCancel="handleHouseholdEditCancel"
      @success="handleAddSuccess"
    />
    <!-- 成员导入 -->
    <Import
      :visible="visibleImport"
      :importUrl="importUrl"
      :title="'导入业户人员'"
      from="householdManagement"
      :downloadTemUrl="downloadTemUrl"
      downloadTemType="downLoad"
      @success="importSuccess"
      @cancelBtn="visibleImport = false"
    />

    <!-- 成员导入结果 -->
    <ImportResult
      :visible="userResultVisible"
      :result="importUserResult"
      :errorUrl="errorUrl"
      @cancelBtn="userResultVisible = false"
    />

    <!-- 租客配置 -->
    <TenantConfig
      :visible="profileVisible"
      @cancel="hideModal"
      @commit="commitHandle"
    />
  </div>
</template>

<script>
import {
  defineComponent,
  ref,
  computed,
  createVNode,
  onActivated,
  reactive,
  toRefs,
} from "vue";
import request from "../../../common/utils/request";
import HouseholdEdit from "./modules/HouseholdEdit.vue";
import { message, Modal, Form } from "ant-design-vue";
import {
  ExclamationCircleOutlined,
  PlusOutlined,
  DownOutlined,
} from "@ant-design/icons-vue";
import store from "../../../store";
import QrcodeVue from "qrcode.vue";
import {useRoute, useRouter} from "vue-router";
import BLCOMMON,{ TenantComponent } from "bl-common-vue3";
import Import from "@/views/setting/DepartmentUser/modules/Import.vue";
import ImportResult from "@/views/setting/DepartmentUser/modules/ImportResult.vue";
import TenantConfig from "./modules/TenantConfig.vue";


const useForm = Form.useForm;

export default defineComponent({
  name: "ownerUser",
  components: {
    HouseholdEdit,
    QrcodeVue,
    PlusOutlined,
    DownOutlined,
    Import,
    ImportResult,
    TenantConfig,
    TenantComponent
  },
  setup() {
    const $router = useRouter();
    const $route = useRoute();

    const state = reactive({
      ownerInput: "",
      buildList: [],
      typeList: [],
      statusList: STATUS_OPTIONS,
      page: 1,
      limit: 10,
      total: 0,
      dataList: [],
      codeList: {},
      importUrl: {
        server: "/village",
        url: "/org/user/import",
      },
      downloadTemUrl: {
        server: "/village",
        url: "/org/user/import/demofile",
      },
      errorUrl: {
        server: "/village",
        url: "/org/user/import/file",
      },
    });

    const searchParams = reactive({
      keywords: "",
      owner_id: undefined,
      build_id: undefined,
      type: undefined,
      status: undefined,
    });

    const { resetFields } = useForm(searchParams, {});

    const reset = () => {
      resetFields();
      getDataList(true);
    };

    const getTypeList = () => {
      request.get("/village", "/user/type/list").then((res) => {
        state.typeList = res.typeList.map((item) => {
          return {
            value: item.type,
            label: item.info,
          };
        });
      });
    };

    const columns = computed(() => {
      return [
        {
          title: "所属业户",
          dataIndex: "owner_name",
          width: store.getters.isMobile ? 130 : undefined,
        },
        {
          title: "人员姓名",
          dataIndex: "name",
          width: store.getters.isMobile ? 130 : undefined,
        },
        {
          title: "手机号",
          dataIndex: "phone",
          width: store.getters.isMobile ? 130 : undefined,
        },
        {
          title: "身份",
          dataIndex: "type_txt",
          width: store.getters.isMobile ? 130 : undefined,
        },
        {
          title: "状态",
          dataIndex: "status_txt",
          key: "status",
          width: store.getters.isMobile ? 130 : undefined,
        },
        {
          title: "操作",
          dataIndex: "id",
          key: "action",
          fixed: "right",
          width: store.getters.isMobile ? 130 : undefined,
        },
      ];
    });

    const selectCancel = (id , data) => {
      searchParams.owner_id = id
    }

    const changeallowes = (id , data) => {
      searchParams.owner_id = id
    }

    const handleAddSuccess = (flag) => {
      if (flag) {
        handleHouseholdEditCancel();
      }
      getDataList();
    };

    const pagination = computed(() => ({
      total: state.total,
      current: state.page,
      pageSize: state.limit,
      showSizeChanger: true,
    }));
    const HouseholdChange = (pager) => {
      state.page = pager.current;
      state.limit = pager.pageSize;
      getDataList();
    };

    // 租客员工列表
    const getDataList = (init = false) => {
      if (init) {
        state.page = 1;
      }
      const params = {
        page: state.page,
        pageSize: state.limit,
      };
      for (let key in searchParams) {
        if (searchParams[key] || searchParams[key] === 0) {
          params[key] = searchParams[key];
        }
      }
      request.get("/village", "/org/user/list", params).then((res) => {
        state.dataList = res.list;
        state.total = res.total;
        state.codeList = res.qrcodeLinkArr;
      });
    };

    onActivated(() => {
      getDataList();
    });

    // 楼宇筛选
    const getBuildList = () => {
      request
        .get("/org", "/build/villageAndBuildList", {
          checked: 1,
        })
        .then((res) => {
          state.buildList = [];
          res.villageList.forEach((village) => {
            village.buildList.forEach((build) => {
              state.buildList.push({
                label: build.build_name,
                value: build.id,
              });
            });
          });
        });
    };


    // ic卡管理
    const ICCardView = (record) => {
      let query = {};
      if (record) {
        query = {
          ownerId: record.owner_id,
          userId: record.id,
        };
      }
      $router.push({
        name: "ICCardList",
        query,
      });
    };

    // 编辑租客员工管理弹窗
    const visible = ref(false);
    // 关闭弹窗
    const btnClose = () => {
      visible.value = false;
    };
    const idEdit = ref(0);
    const ownerInfoEdit = ref({});
    const HouseholdEdit = (value) => {
      visible.value = true;
      idEdit.value = value ? value.id : 0;
      ownerInfoEdit.value = { id: value?.owner_id };
    };
    const Modals = ref(false);
    const HouseholdDelet = (value) => {
      Modals.value = true;
      Modal.confirm({
        title: `确认删除该业户人员吗？`,
        icon: createVNode(ExclamationCircleOutlined),
        okText: "确认",
        cancelText: "取消",
        onOk() {
          request
            .del("/village", "/org/user/delete", {
              id: value.id,
              village_id: value.village_id,
            })
            .then((res) => {
              message.success("删除成功");
              getDataList();
            });
        },
      });
    };

    const buildPlaceholder = computed(() => {
      return `请选择${BLCOMMON.utils.L("楼宇")}`;
    });

    // 导入成员
    const visibleImport = ref(false);
    // 导入成员结果
    const importUserResult = ref({});
    // 结果展示
    const userResultVisible = ref(false);

    const btnUserImport = () => {
      visibleImport.value = true;
    };

    // 租客配置
    const profileVisible = ref(false);
    const userProfile = () => {
      profileVisible.value = true;
    };
    const commitHandle = () => {
      profileVisible.value = false;
    };
    const hideModal = () => {
      profileVisible.value = false;
    };

    const importSuccess = (data) => {
      visibleImport.value = false;
      // 刷新列表
      getDataList();
      importUserResult.value = data;
      userResultVisible.value = true;
    };

    const handleHouseholdEditCancel = () => {
      visible.value = false;
      idEdit.value = 0;
      ownerInfoEdit.value = {};
    };
    const init = () => {
      if ($route.query?.status) {
        searchParams.status = Number($route.query.status);
      }
      getBuildList();
      getTypeList();
    };

    init();

    return {
      HouseholdEdit,
      HouseholdChange,
      HouseholdDelet,
      btnClose,
      pagination,
      columns,
      visible,
      idEdit,
      ownerInfoEdit,
      ICCardView,
      searchParams,
      ...toRefs(state),
      handleAddSuccess,
      getDataList,
      reset,
      buildPlaceholder,
      visibleImport,
      importUserResult,
      userResultVisible,
      importSuccess,
      btnUserImport,
      userProfile,
      profileVisible,
      commitHandle,
      hideModal,
      handleHouseholdEditCancel,

      selectCancel,
      changeallowes
    };
  },
});

const STATUS_OPTIONS = [
  {
    value: 0,
    label: "待审核",
  },
  {
    value: 1,
    label: "已审核",
  },
  {
    value: 4,
    label: "被拒绝",
  },
];
</script>

<style lang="less" scoped>
.code-box {
  width: 100%;
  max-height: 800px;
  overflow-y: auto;
  .code {
    margin: 10px auto;
  }
}
:deep(.ant-table.ant-table-bordered .ant-table-title) {
  border: 1px solid #fff;
}
:deep(.ant-btn-link) {
  margin-right: 0;
}
</style>
